package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"prac3/cache"
	"prac3/model"
	"prac3/pkg"
	"strconv"
	"time"
)

func CarOrderDetail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var list model.CarOrderList
	redis_key := "car_order_detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	/*
		SELECT
		  cars.car_code CarCode,
		  cars.car_name CarName,
		  car_orders.order_code OrderCode,
		  car_orders.order_price OrderPrice
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
		WHERE
		  car_orders.id = 2
	*/
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select(
				"cars.car_code CarCode",
				"cars.car_name CarName",
				"car_orders.order_code OrderCode",
				"car_orders.order_price OrderPrice",
			).
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Where("car_orders.id = ?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"mag":  "ok",
		"data": list,
	})
	return
}

func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []model.CarOrderList
	var total int64
	model.DB.Model(&model.CarOrder{}).Count(&total)
	redis_key := "car_order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	/*
		SELECT
		  cars.car_code CarCode,
		  cars.car_name CarName,
		  car_orders.order_code OrderCode,
		  car_orders.order_price OrderPrice
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
		WHERE
		  car_orders.id = 2
	*/
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select(
				"cars.car_code CarCode",
				"cars.car_name CarName",
				"car_orders.order_code OrderCode",
				"car_orders.order_price OrderPrice",
			).
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Offset(offset).Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"mag":   "ok",
		"data":  list,
		"total": total,
	})
	return
}

func CarOrderAdd(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order_code := c.PostForm("order_code")
	order_price := c.PostForm("order_price")
	data := model.CarOrder{
		Cid:        cid,
		OrderCode:  order_code,
		OrderPrice: order_price,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "订单添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
	})
	return
}

func CarAdd(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	if car_code == "" || car_name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能空",
		})
		return
	}
	data := model.Car{
		CarCode: car_code,
		CarName: car_name,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var total int64
	var user []model.User
	model.DB.Model(&user).Count(&total)
	redis_key := "user_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  user,
		"total": total,
	})
	return
}

func RoleNode(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/
	rid := c.Query("rid")
	var nodes []model.Node
	redis_key := "user_role_" + rid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("nodes").
			Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
			Where("role_nodes.rid = ?", rid).
			Find(&nodes)
	} else {
		json.Unmarshal([]byte(cacheData), &nodes)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
	return
}

func UserRole(c *gin.Context) {
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	uid := c.Query("uid")
	var role []model.Role
	redis_key := "user_role_" + uid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("roles").
			Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
			Where("user_roles.uid =?", uid).
			Find(&role)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户角色关联失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户角色关联失败",
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色权限关联失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色权限关联成功",
	})
	return
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能空",
		})
		return
	}
	redis_key := "error_" + username
	errorCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errorCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "已禁封",
		})
		return
	}
	var user model.User
	if err := model.DB.Where("username=?", username).Find(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errorCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次禁封两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误请重新输入",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  user,
		"token": token,
	})
	return
}
func Info(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"uid":  uid,
	})
}
